package com.dstats.fragments;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.adapter.NewsAdapter;
import com.dstats.R;
import com.entities.News;
import com.fetch.ReadXMLFile;

public abstract class VodsFragment extends Fragment {
	  private ListView listView;
	  private ProgressBar progressBarNewsFragment;
	  protected abstract void fetch();
	  
		private void setAdapterAndListener(List<News> list){
			if(list!=null){
				listView.invalidate();
				listView.setAdapter(new NewsAdapter(getActivity().getApplicationContext(), list, true));
				listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> adapter, View view, int arg2,
						long arg3) {
					
					Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(((News) adapter.getItemAtPosition(arg2)).getLink()));
					startActivity(browserIntent);
				}
				
			});
			}
		}
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	             Bundle savedInstanceState) {
			
	        View rootView = inflater.inflate(R.layout.news_fragment, container, false);
	        progressBarNewsFragment = (ProgressBar) rootView.findViewById(R.id.progressBarNewsFragment);
	        listView = (ListView) rootView.findViewById(R.id.listViewNews);
	        setAdapterAndListener(News.youTubeNews.get(getVodTag()));
			//List<News> news = News.getNewsYouTube(getUrl(), null);
	        if(News.youTubeNews.get(getVodTag())==null){
	        	fetch();
	        }
	        return rootView;
	  }
	
	class FetchYouTube extends AsyncTask<Void, Void, List<News>>{
		private List<String> urls;
		public FetchYouTube(List<String> urls) {
		this.urls = urls;
		
		}
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progressBarNewsFragment.setVisibility(View.VISIBLE);
			progressBarNewsFragment.setIndeterminate(true);
		}

		@Override
		protected List<News> doInBackground(Void... params) {
			List<List<String>> list = new ArrayList<List<String>>();
			InputStream stream = null;
			for(String url: urls){
			try {
				
				URL urlt = new URL(url);
				HttpURLConnection conn = (HttpURLConnection) urlt.openConnection();
				conn.setReadTimeout(10000 /* milliseconds */);
				conn.setConnectTimeout(15000 /* milliseconds */);
				conn.setRequestMethod("GET");
				conn.setDoInput(true);
				conn.connect();
				stream = conn.getInputStream();
				list.addAll(ReadXMLFile.parse(stream, News.tagName, News.fieldNames));
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			}
			
			
			List<News> newsList = News.getYouTube(list, getVodTag());
			
			class DateComparator implements Comparator<News> {
			    public int compare(News otherNews, News news) {
			        return news.getDate().
			                compareTo(otherNews.getDate());
			    }
			}
			
			DateComparator comparator = new DateComparator();
			
			Collections.sort(newsList , comparator);
			
			return newsList;
		}
		
		@Override
		protected void onPostExecute(final List<News> result) {
			super.onPostExecute(result);			
			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {
					setAdapterAndListener(result);	
					progressBarNewsFragment.setVisibility(View.INVISIBLE);
				}
			});			
		}
		
		
		
	}
	
	protected abstract String getVodTag();
	protected abstract List<String> getUrl();

}
